package kwic.es;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

public class WordIndex implements Observer {

	Map<String, Integer> index = new LinkedHashMap<String, Integer>();

	@Override
	public void update(Observable observable, Object arg) {
		LineStorageWrapper lines = (LineStorageWrapper) observable;
		LineStorageChangeEvent event = (LineStorageChangeEvent) arg;
		switch (event.getType()) {
		case LineStorageChangeEvent.ADD:
			String[] line = lines.getLine(lines.getLineCount() - 1);
			for (int i = 0; i < line.length; i++) {
				if (index.keySet().contains(line[i])) {
					int count = index.get(line[i]);
					index.put(line[i], count + 1);
				} else {
					index.put(line[i], 1);
				}
			}
			break;
		case LineStorageChangeEvent.DELETE:
			String linePatternToDelete = event.getArg();
			String[] words = linePatternToDelete.split(" ");
			for (int i = 0; i < words.length; i++) {
				int count = index.get(words[i]);
				if (count > 1) {
					index.put(words[i], count - 1);
				} else {
					index.remove(words[i]);
				}
			}
		default:
			break;
		}
	}

	public void print() {
		for (String word : index.keySet()) {
			System.out.println(word + ": " + index.get(word));
		}
	}
}
